package cn.joker.services.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.joker.constant.Result;
import cn.joker.entity.po.Permissions;
import cn.joker.entity.po.Systems;
import cn.joker.entity.vo.PermissionTreeVO;
import cn.joker.exception.BusinessException;
import cn.joker.mapper.PermissionsMapper;
import cn.joker.services.IPermissionService;
import cn.joker.util.PermissionTreeConverter;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class PermissionServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements IPermissionService {
    @Override
    public Result<List<PermissionTreeVO>> getPermissionTree(Systems systems) {
        List<Permissions> list = lambdaQuery().eq(Permissions::getSystemCode, systems.getSystemCode()).list();
        List<PermissionTreeVO> permissionTreeVOS = PermissionTreeConverter.buildPermissionTree(list);
        return Result.success(permissionTreeVOS);
    }

    @Override
    public Result<String> addPermission(Permissions permissions) {
        if (StrUtil.isEmpty(permissions.getSystemCode())) {
            throw new BusinessException("未选择所属项目！");
        }
        if (StrUtil.isEmpty(permissions.getPermissionCode())) {
            permissions.setPermissionCode(UUID.randomUUID().toString());
            permissions.setCreateTime(LocalDateTime.now());
            permissions.setUpdateTime(LocalDateTime.now());
            save(permissions);
            return Result.success("新增成功!");
        } else {
            updateById(permissions);
            return Result.success("修改成功!");
        }

    }

    @Override
    public Result<Permissions> getPermissionByCode(Permissions permissions) {
        return Result.success(lambdaQuery().eq(Permissions::getPermissionCode, permissions.getPermissionCode()).one());
    }
}
